package pl.elka.pszt.model.parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

/**
 * Czyta podany plik linijka po linijce.
 * @author Andrzej Makarewicz
 * 
 */
public class FileLineReader {
	
	private FileLineReader() {}
	
	private static final String RESOURCES_DIR = "/pl/elka/pszt/resources/";
	
	public static boolean readFromResource(String fileName, LineParser parser) {
		URL url = fileName.getClass().getResource(RESOURCES_DIR + fileName);
		File file = new File(url.getFile());
		
		return readFile(file, parser);
	}
	
	public static boolean readFile(File file, LineParser parser) {
		try {
			BufferedReader input = new BufferedReader(new FileReader(file));
			try {
				String line = null;
				while ((line = input.readLine()) != null) {
					parser.parseLine(line);
				}
			}
			finally {
				input.close();
			}
		}
		catch (IOException ex) {
			ex.printStackTrace();
			
			return false;
		}
		
		return true;
	}
	
	public interface LineParser {
		void parseLine(String line);
	}
}
